package com.gdou.service.impl;

import com.gdou.commons.Result;
import com.gdou.mapper.DeptMapper;
import com.gdou.dto.DeptDto;
import com.gdou.model.Dept;
import com.gdou.service.DeptService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public Result findAllDepts() {
        List<Dept> depts = deptMapper.selectAll();
        Result result = Result.SUCCESS;
        result.setData(depts);
        return result;
    }

    @Override
    public Result findDeptsByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Dept> depts = deptMapper.selectAll();
        PageInfo<Dept> deptPageInfo = new PageInfo<>(depts);
        Result result = new Result();
        result.setData(deptPageInfo.getList());
        result.setTotal(deptPageInfo.getTotal());
        return result;
    }

    @Override
    public Result saveDepts(DeptDto deptDto) {
        int rows = deptMapper.insertDepts(deptDto);
        if (rows<1){
            return new Result(-1,"部门添加失败");
        }
        return new Result();
    }

    @Override
    public Result deleteDept(Long id) {

        int rows= deptMapper.deleteDept(id);
        if (rows<1){
            return new Result(-1,"部门删除失败");
        }
        return new Result();
    }

    @Override
    public Result editDept(Dept dept) {
        if (dept.getId()==null){
            return Result.DATA_FORMAT_ERROR;
        }else if (!StringUtils.hasText(dept.getName())){
            return Result.DATA_FORMAT_ERROR;
        }else if (!StringUtils.hasText(dept.getLoc())){
            return Result.DATA_FORMAT_ERROR;
        }
       int rows= deptMapper.modifyDept(dept);
        if (rows<1){
            return new Result(-1,"部门修改失败");
        }
        return new Result();
    }
}
